package com.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

class TransferInfo implements Runnable {
    //收集两个客户端
    private Socket gnss = null;
    private Socket ntripServer = null;

    InputStream inputStream = null;
    OutputStream outputStream = null;

    public TransferInfo(Socket gnss, Socket ntripServer) {
        this.gnss = gnss;
        this.ntripServer = ntripServer;
    }

    @Override
    public void run() {
        if (gnss == null) {
            System.out.println("ntripServer已连接，gnss未连接");
        } else if (ntripServer == null) {
            System.out.println("gnss已连接，ntripServer未连接");
        } else {//都连接后，从gnss的inputstream读数据到ntripServer的outputstream
            System.out.println("都已连接，开始转发数据");
            try {
                while (true) {
                    inputStream = gnss.getInputStream();
                    outputStream = ntripServer.getOutputStream();
                    int len;
                    byte[] buffer = new byte[1024];
                    while ((len = inputStream.read(buffer)) > 0) {
                        outputStream.write(buffer, 0, len);
                        outputStream.flush();
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (outputStream != null) {
                    try {
                        outputStream.close();
                        System.out.println("输出流关闭");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (inputStream != null) {
                    try {
                        inputStream.close();
                        System.out.println("输入流关闭");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (ntripServer != null) {
                    try {
                        ntripServer.close();
                        System.out.println("ntripServer关闭");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (gnss != null) {
                    try {
                        gnss.close();
                        System.out.println("gnss关闭");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }
}